﻿using System;
using System.Linq;
using System.Net;
using System.Reflection;
using Ping.Core;
using log4net;

namespace Ping.Server.Jobs
{
	/// <summary>
	/// Resolves a domain into one or more ip addresses.
	/// </summary>
	public sealed class DnsJob
		: Job
	{
		private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		public override Type RequestType
		{
			get { return typeof (DnsRequest); }
		}

		public override Type ResultType
		{
			get { return typeof (DnsResult); }
		}

		public override string Name
		{
			get { return "DNS"; }
		}

		public override Result Perform(Request request)
		{
			var tmp = (DnsRequest) request;

			if (Log.IsDebugEnabled)
				Log.DebugFormat("Performing lookup for {0}", tmp.Domain);

			IPAddress[] addresses = Dns.GetHostAddresses(tmp.Domain);

			if (Log.IsDebugEnabled)
				Log.DebugFormat("{0} has {1} address(es)", tmp.Domain, addresses.Length);

			return new DnsResult
			       	{
			       		Addresses = (from a in addresses
			       		             select new IpAddress(a)).ToArray(),
			       	};
		}
	}
}